 //
//  RequestManager.m
//  片刻
//
//  Created by lanou3g on 15/6/4.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "RequestManager.h"


@implementation RequestManager

- (void)dealloc
{
    NSLog(@"====");
    self.requestParameter = nil;
    self.requestURL = nil;
    self.data = nil;
    [super dealloc];
}

-(instancetype)initWithRequestURL:(NSString *)urlString requestModel:(RequestModel)requestModel parameter:(NSString *)parameter
{
    self = [super init];
    if (self) {
        _requestURL = urlString;
        _requestParameter = parameter;
        _requestModel = requestModel;
        _parameterDic = [[NSMutableDictionary alloc] init];
    }
    return self;
}

//开始请求。
-(void)startRequest
{
    NSURL *url = [NSURL URLWithString:_requestURL];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    if (_requestModel == POST) {
        [request setHTTPMethod:@"POST"];
        [self parameterDicToString];
        [request setHTTPBody:[_requestParameter dataUsingEncoding:NSUTF8StringEncoding]];
    }
    [NSURLConnection connectionWithRequest:request delegate:self];
}

- (void)parameterDicToString
{
    if (_parameterDic.count != 0) {
        NSMutableArray *parameterArray = [NSMutableArray array];
        for (NSString *key in _parameterDic) {
            NSString *str = [NSString stringWithFormat:@"%@=%@",key,_parameterDic[key]];
            [parameterArray addObject:str];
        }
        
#warning 这个方法会把数组里的元素连接起来，以给的参数（&）来连接，最后形成一个字符串返回。
#warning 这里不能写_requestParameter而应写self.requestParameter,因为这里的字符串是写在了堆区，写_requestParameter的话会在程序运行时造成过渡释放使方法发给一个已经被释放的对象即—_requestParameter，如果仅仅是简单地字符串，则会写在常量区，例如NSString *str = @"123"，123就写在了常量区，这时候对str释放多少次都没关系，但字符串很长或很大时则会写到堆区，则要注意字符串对象的释放，以防止出现野指针，即堆区内容已被释放，对象指针如str仍存在并指向一个没有内容的对内存。
        self.requestParameter = [parameterArray componentsJoinedByString:@"&"];
    }
//    NSLog(@"%@___elf", self);
}

#pragma mark - NSURLConnectionDataDelegate

//拼接返回的data，此方法可能会多次执行。
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.data appendData:data];
}
//开始响应请求的方法，在这里对自己的data进行初始化。
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    self.data = [NSMutableData data];
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    if (_delegate && [_delegate respondsToSelector:@selector(requestError:)]) {
        [_delegate requestError:error];
    }
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    if (_delegate && [_delegate respondsToSelector:@selector(requestDidFinishWithData:)]) {
        
        [_delegate requestDidFinishWithData:self.data];
    }
}



@end
